<template>
	<view class="app">
		<Header :isBack="true">
			<block slot="content">{{title}}</block>
		</Header>
		<view class="price-box">
			<text>支付金额</text>
			<text class="price">{{total}}</text>
		</view>

		<view class="pay-type-list" v-if="this.total">

			<view class="type-item b-b" @click="changePayType(1)">
				<text class="icon yticon icon-weixinzhifu"></text>
				<view class="con">
					<text class="tit">微信支付</text>
					<text>推荐使用微信支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == 1' />
					</radio>
				</label>
			</view>
			<!-- <view class="type-item b-b" v-if="!isWechat" @click="changePayType(2)">
				<text class="icon yticon icon-alipay"></text>
				<view class="con">
					<text class="tit">支付宝支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == 2' />
					</radio>
				</label>
			</view> -->
			<!-- <view class="type-item" @click="changePayType(3)">
				<text class="icon yticon icon-erjiye-yucunkuan"></text>
				<view class="con">
					<text class="tit">预存款支付</text>
					<text>可用余额 ¥198.5</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == 3' />
					</radio>
				</label>
			</view> -->
		</view>

		<text class="mix-btn" @click="confirm" v-if="isPay">确认支付</text>
		<text class="mix-btn" style="background-color: #999;" v-else>支付中...</text>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: '支付订单',
				total: 0.00,
				payType: 1,
				isPay: true,
				orderInfo: {},
				// baseUrl: 'https://test.hnliandesy.com/api/',
				baseUrl: 'https://test.hnliandesy.com/api/',
				tag: '',
				isWechat: false,
				appid: "wx5f6ba2c4d12e2e1f",
				openId: '',
				mobile: '',
				type: 2
			};
		},
		computed: {

		},
		onLoad(options) {
			if (options.money >= 0) {
				this.total = options.money
				uni.setStorageSync('total', options.money);
			} else {
				this.total = uni.getStorageSync('total');
			}

			this.tag = uni.getStorageSync('tag')

			uni.getStorage({
				key: 'userInfo',
				success: (res) => {
					this.mobile = res.data.mobile
				}
			});

			// #ifdef H5
			if (this.$wechat && this.$wechat.isWechat()) {
				this.isWechat = true;

				//微信公众号登录
				if (!this.openId) {
					if (window.location.href.indexOf('?code=') !== -1 || window.location.href.indexOf('&code=') !== -1) {
						this.isPay = false;
						let code;
						if (window.location.href.indexOf('?code=') !== -1) {
							code = window.location.href.split('?code=')[1].split('&')[0];
						} else {
							code = window.location.href.split('&code=')[1].split('&')[0];
						}
						//请求后端网络请求
						this.getWxOpenId(code);
					}
				}
			}
			// #endif

			// #ifdef MP-WEIXIN
			this.isWechat = true;
			// #endif
		},

		methods: {
			//选择支付方式
			changePayType(type) {
				this.payType = type;
			},

			async getWxOpenId(code) {
				let res = await this.$myRequest({
					url: '/getWxOpenId',
					data: {
						code: code
					}
				})

				this.openId = res.data.data.openid
				this.confirmPay();
			},

			async confirmPay() {
				uni.showLoading({
					title: '加载中'
				});
				let token = uni.getStorageSync('token');
				if (!token) {
					this.$api.msg('请重新登录', 'none'),
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						}, 1000)
				}
				let tag = this.tag
				if (!tag) {
					this.$api.msg('非法操作！');
					return false;
				}
				let dataObj = {
					token: token,
					cate: uni.getStorageSync('cate'),
					tag: tag,
					paytype: 1,
					type: this.type,
					openid: this.openId
				}

				let res = await this.$myRequest({
					url: '/goPay',
					data: dataObj,
					methods: 'POST',
				})

				if (res.data.status == 2) {
					let info = res.data.data
					WeixinJSBridge.invoke(
						'getBrandWCPayRequest', {
							"appId": info.appId, //公众号名称，由商户传入     
							"timeStamp": info.timeStamp, //时间戳，自1970年以来的秒数     
							"nonceStr": info.nonceStr, //随机串     
							"package": info.package,
							"signType": info.signType, //微信签名方式：     
							"paySign": info.paySign //微信签名 
						},
						(res) => {
							if (res.err_msg == "get_brand_wcpay_request:ok") {
								this.payMaskHide = true; // 隐藏当前支付方式选择

								this.sendNotice(this.mobile)

								uni.redirectTo({
									url: '/pages/money/paySuccess'
								})
							} else {
								this.$api.msg('支付失败！')
								this.isPay = true;
							}
						}
					)
				} else if (res.data.status == 1) {

					let paymentData = res.data.data;
					uni.requestPayment({
						timeStamp: paymentData.timeStamp,
						nonceStr: paymentData.nonceStr,
						package: paymentData.package,
						signType: 'MD5',
						paySign: paymentData.paySign,
						success: (res) => {

							this.sendNotice(this.mobile)

							uni.redirectTo({
								url: '/pages/money/paySuccess'
							})
						},
						fail: (res) => {
							this.$api.msg('支付失败！')
							this.isPay = true;
						}
					})
				} else {
					this.$api.msg('非法操作！')
				}

				uni.hideLoading()
			},

			//确认支付
			confirm: async function() {
				let tag = this.tag
				if (!tag) {
					this.$api.msg('非法操作！');
					return false;
				}
				this.isPay = false

				let dataObj = {
					token: uni.getStorageSync('token'),
					cate: uni.getStorageSync('cate'),
					tag: tag,
					paytype: this.payType
				}

				// #ifdef H5
				if (this.$wechat && this.$wechat.isWechat()) {
					//微信浏览器
					this.getAccessToken();
				} else {
					//非微信浏览器
					dataObj.type = 3;
					switch (this.payType) {
						case 1:
							this.wxPayH5(dataObj);
							break;
						case 2:
							let res = await this.$myRequest({
								url: '/goPay',
								data: dataObj,
								methods: 'POST',
							})

							let payInfo = res.data

							if (payInfo) {
								document.querySelector('.form').innerHTML = payInfo;
								document.forms[0].submit();
							}
							break;
					}
				}
				// #endif

				// #ifdef APP-PLUS
				dataObj.type = 4;
				switch (this.payType) {
					case 1:
						this.wxPay(dataObj);
						break;
					case 2:
						this.aliPay(dataObj);
						break;
				}

				// #endif

				// #ifdef MP-WEIXIN
				var that = this
				uni.login({
					provider: "weixin",
					success(loginAuth) {
						that.getOpenId(loginAuth.code)
					}
				})

				// #endif
			},

			async getOpenId(code) {
				let res = await this.$myRequest({
					url: '/getAppletOpenId',
					data: {
						code: code
					},
					methods: 'post'
				})

				if (res.data.status == 1) {
					this.openId = res.data.data
					this.type = 1
					this.confirmPay()
				}
			},

			//支付宝支付
			async aliPay(dataObj) {
				uni.getProvider({ //获取可用的支付环境
					service: 'payment',
					success: res => {
						if (~res.provider.indexOf('alipay')) { //先判断用户是否有支付宝支付环境
							uni.showLoading({
								title: '正在调起支付宝支付'
							})

							uni.request({ //再从后端接口获取相关数据配置到orderInfo里，这个接口由后端配置好了，返回结果见下图1-支付宝
								url: this.baseUrl + 'goPay',
								method: 'POST',
								data: dataObj,
								dataType: "json",
								success: res => {
									if (res.statusCode == 200) {
										if (res.data.status == 0) {
											this.$api.msg(res.data.msg);
											return false;
										}
										let payInfo = res.data //拿到后端返回数据后调用下面支付函数（若接口返回obj,需先转成string类型）
										console.log(payInfo);return ;
										payInfo = payInfo.replace(/\r|\n/ig, "")
										uni.requestPayment({
											provider: 'alipay',
											orderInfo: payInfo, //支付宝订单数据（string类型）
											success: res => {
												uni.hideLoading();
												this.sendNotice(this.mobile)
												uni.redirectTo({
													url: '/pages/money/paySuccess'
												})
											},
											fail: err => {
												uni.hideLoading();
												this.$api.msg('支付失败！');
												this.isPay = true
											}
										});
									}
								},
								fail: () => {
									uni.hideLoading();
									this.$api.msg('服务器开小差了呢，请您稍后再试');
								}
							});
						} else {
							uni.showToast({
								title: '获取支付宝通道失败，请检查您的支付宝是否正常启用',
								icon: 'none'
							})
						}
					}
				});
			},

			//微信支付
			wxPay(dataObj) {
				uni.getProvider({
					service: 'payment',
					success: res => {
						if (~res.provider.indexOf('wxpay')) { //先判断用户是否有微信支付环境（是否安装了微信app）
							uni.showLoading({
								title: '正在调起微信支付'
							})

							uni.request({
								url: this.baseUrl + 'goPay',
								method: 'POST',
								data: dataObj,
								dataType: "json",
								success: (res) => {
									if (res.data.status == 4) {
										//（这里注意后端返回的数据类型是string还是object，需转成object类型）
										let resobj = res.data.data;
										console.log(resobj)
										let payInfo = {
											appid: resobj.appid,
											noncestr: resobj.nonce_str,
											package: "Sign=WXPay",
											partnerid: resobj.mch_id,
											prepayid: resobj.prepay_id,
											timestamp: resobj.time_stamp,
											sign: resobj.sign,
										}

										uni.requestPayment({
											provider: 'wxpay',
											orderInfo: payInfo, //微信订单数据（Object类型）
											success: (res) => {
												uni.hideLoading();
												this.sendNotice(this.mobile)
												uni.redirectTo({
													url: '/pages/money/paySuccess'
												})
											},
											fail: (err) => {
												uni.hideLoading();
												this.$api.msg('支付失败！');
												this.isPay = true
											}
										});
									} else if (res.data.status == 0) {
										this.$api.msg(res.data.msg);
									}
								},
								fail: (err) => {
									uni.hideLoading();
									this.$api.msg('服务器开小差了呢，请您稍后再试');
								}
							})
						} else {
							uni.showToast({
								title: '获取微信通道失败，请检查您的微信是否正常启用',
								icon: 'none'
							})
						}
					}
				});
			},

			async wxPayH5(dataObj) {
				let res = await this.$myRequest({
					url: '/goPay',
					data: dataObj,
					methods: 'POST',
				})

				if (res.data.status == 3) {
					let info = res.data.data
					window.location.href = info;
				}
			},

			async getAccessToken() {
				//重点 这里getWxAppid这个是微信公众号的appid
				if (!this.openId) {
					window.location.href =
						'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
						this.appid +
						'&redirect_uri=' + encodeURIComponent(
							'https://test.hnliandesy.com/h5/#/pages/money/pay') +
						'&response_type=code&scope=snsapi_userinfo#wechat_redirect';
				} else {
					this.confirmPay();
				}
			},

			async sendNotice(mobile) {
				let res = await this.$myRequest({
					url: '/sendNotice/' + mobile,
				})
			}
		}
	}
</script>
<style>
	page {
		background-color: #f7f7f7;
		font-size: $font-base;
	}
</style>
<style lang='scss'>
	.app {
		width: 100%;
		// #ifdef APP-PLUS
		padding-top: 160rpx;
		// #endif

		// #ifdef H5
		padding-top: 110rpx;
		// #endif

		// #ifdef MP-WEIXIN
		padding-top: 144rpx;
		// #endif
	}

	.price-box {
		background-color: #fff;
		height: 265upx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 28upx;
		color: #909399;

		.price {
			font-size: 50upx;
			color: #303133;
			margin-top: 12upx;

			&:before {
				content: '￥';
				font-size: 40upx;
			}
		}
	}

	.pay-type-list {
		margin-top: 20upx;
		background-color: #fff;
		padding-left: 60upx;

		.type-item {
			height: 120upx;
			padding: 20upx 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-right: 60upx;
			font-size: 30upx;
			position: relative;
		}

		.icon {
			width: 100upx;
			font-size: 52upx;
		}

		.icon-erjiye-yucunkuan {
			color: #fe8e2e;
		}

		.icon-weixinzhifu {
			color: #36cb59;
		}

		.icon-alipay {
			color: #01aaef;
		}

		.tit {
			font-size: $font-lg;
			color: $font-color-dark;
			margin-bottom: 4upx;
		}

		.con {
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: $font-sm;
			color: $font-color-light;
		}
	}

	.mix-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 630upx;
		height: 80upx;
		margin: 80upx auto 30upx;
		font-size: $font-lg;
		color: #fff;
		background-color: $base-color;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
	}
</style>
